package org.xmlrpc.android;

import org.apache.http.conn.HttpHostConnectException;

import android.os.Handler;
import android.util.Log;

public class XMLRPCMethod extends Thread {
	private XMLRPCClient client;
	private String method;
	private Object[] params;
	private Handler handler;
	private XMLRPCMethodCallback callBack;

	public XMLRPCMethod(XMLRPCClient client, String method, XMLRPCMethodCallback callBack) {
		this.client = client;
		this.method = method;
		this.callBack = callBack;
		handler = new Handler();
	}

	public void call() {
		call(null);
	}

	public void call(Object[] params) {
		/*status.setTextColor(0xff80ff80);
		status.setError(null);
		status.setText("Calling host: " + uri.getHost() + 
				((uri.getPort() == -1) ?"":":" + uri.getPort())
			);
		tests.setEnabled(false);*/
		this.params = params;
		start();
	}

	@Override
	public void run() {
		try {
			final long t0 = System.currentTimeMillis();
			final Object result = client.callEx(method, params);
			final long t1 = System.currentTimeMillis();
			handler.post(new Runnable() {
				public void run() {
					/*tests.setEnabled(true);
					status.setText("XML-RPC call took " + (t1 - t0) + "ms");*/
					callBack.callFinished(result);
				}
			});
		} catch (final XMLRPCFault e) {
			handler.post(new Runnable() {
				public void run() {
					/*testResult.setText("");
					tests.setEnabled(true);
					status.setTextColor(0xffff8080);
					status.setError("", errorDrawable);
					status.setText("Fault message: " + e.getFaultString()
							+ "\nFault code: " + e.getFaultCode());*/
					Log.d("Test", "error", e);
				}
			});
		} catch (final XMLRPCException e) {
			handler.post(new Runnable() {
				public void run() {
					/*testResult.setText("");
					tests.setEnabled(true);
					status.setTextColor(0xffff8080);
					status.setError("", errorDrawable);*/
					Throwable couse = e.getCause();
					if (couse instanceof HttpHostConnectException) {
						/*status.setText("Cannot connect to "
								+ uri.getHost() + ":" + uri.getPort()
								+ "\nMake sure GarminPCSync on your development host is running !!!");*/
					} else {
						//status.setText("Error " + e.getMessage());
					}
					Log.d("Test", "error", e);
				}
			});
		} finally {
			
		}
	}
}
